package cn.lianyutiantang.base.commons;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhengjl
 * @ClassName CloudClientUtil
 * @Description TODO
 * @Date 2018/9/1621:41
 * @Version 1.0
 **/
public class CloudClientUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(CloudClientUtil.class);

    @Autowired
    RestTemplate restTemplate;


    /**
     * 微服务提交JSON请求
     *
     * @param url           请求地址
     * @param requestObject 请求对象
     * @param responseType  返回类型
     * @param <T>
     * @return
     */
    public static <T> T postJson(String url, Object requestObject, Class<T> responseType) {
        try {
            return getClient().postForObject(url, requestObject, responseType);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    /**
     * 微服务发送Get请求
     *
     * @param url          请求地址,地址或当参数也可以
     * @param responseType 返回类型
     * @param <T>
     * @return
     */
    public static <T> T getForObject(String url, Class<T> responseType) {
        try {
            return getClient().getForObject(url, responseType);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获得一个RestTemplate客户端
     *
     * @return
     */
    public static RestTemplate getClient() {
        return CloudRestTemplateConfig.getClient();
    }
}
